package com.irdstudio.efp.esb.api.rest.psd.credit;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.esb.api.bean.psd.credit.req.PsdCreditApplyReqBean;
import com.irdstudio.efp.esb.api.bean.psd.credit.req.PsdCreditBackReqBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceHandler;
import com.irdstudio.efp.esb.api.common.GroupeInterface;
import com.irdstudio.efp.esb.api.rest.EsbController;
import com.irdstudio.efp.esb.api.service.psd.credit.PsdCreditBackService;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.loan.service.vo.LoanRepayDetailVO;
import com.irdstudio.efp.nls.service.facade.PsdSendTaxRecordService;
import com.irdstudio.efp.nls.service.facade.psd.PreNlsCreditInfoService;
import com.irdstudio.efp.nls.service.facade.psd.QuotaCheckService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.PsdSendTaxRecordVO;
import com.irdstudio.efp.nls.service.vo.psd.PreNlsCreditInfoVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("/esb")
public class PsdCreditBackController implements EsbController {
    /**
     * 日志信息
     */
    private final Logger logger = LoggerFactory.getLogger(PsdCreditBackController.class);

    @Autowired
    private QuotaCheckService quotaCheckService;

    @Autowired
    private PsdSendTaxRecordService psdSendTaxRecordService;

    @Autowired
    private PubSysInfoService pubSysInfoService;

    @Autowired
    private NlsCreditInfoService nlsCreditInfoService;

    @Autowired
    private PreNlsCreditInfoService preNlsCreditInfoService;

    @PostMapping("/SERVICE_30220009_07")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult bindingResult1,
                                     @Validated({GroupeInterface.psd.class}) @ModelAttribute("psdCreditBackReqBean") PsdCreditBackReqBean psdCreditBackReqBean, BindingResult bindingResult2, Exception exception) {
        // 全局关联流水号
        String glblSrlNo = esbReqServiceBean.getSysHead().getGlblSrlNo();
        try {
            // 参数校验
            validateBean(esbReqServiceBean, bindingResult1, psdCreditBackReqBean, bindingResult2, exception, logger);

            logger.info("======>调用接口【" + glblSrlNo + "30220009_07】开始<======");

            // 设置系统头对象
            setSysHeadFieldThreadLocal(esbReqServiceBean);

            if ("Y".equals(psdCreditBackReqBean.getAprvlRsltFlg().trim())) {
                // 审批成功则更新占用额度
                quotaCheckService.updatePreOccupied(psdCreditBackReqBean.getCrAppSrlNo(), psdCreditBackReqBean.getLoanAplLmt());
            }
            // 回写税局
            insertTaxRecord(psdCreditBackReqBean);

            psdApplyBackService.processApply(psdCreditBackReqBean);

            // 执行授信请求流程并返回
            return EsbRespServiceHandler.esbSuccessHandler(esbReqServiceBean);

        } catch (ESBException e) {
            logger.error("授信申请风控审批回调发生异常：",e);
            return EsbRespServiceHandler.esbFailureHandler(esbReqServiceBean, e.getErrorCode(), e.getMessage());
        } catch (BizException e) {
            logger.error("授信申请风控审批回调发生异常：",e);
            return EsbRespServiceHandler.esbFailureHandler(esbReqServiceBean, e.getErrorCode(), e.getMessage());
        } finally {
            //删除占用额度
            clearPreOccupied(psdCreditBackReqBean.getCrAppSrlNo());
            logger.info("======>调用接口【" + glblSrlNo + "_30220009_07】结束<======");
        }
    }

    public void insertTaxRecord(PsdCreditBackReqBean psdCreditBackReqBean) {
        try {

            NlsCreditInfoVO nlsCreditInfoVO = nlsCreditInfoService.queryByLmtApplySeq(psdCreditBackReqBean.getCrAppSrlNo());
            PreNlsCreditInfoVO preNlsCreditInfoPk = new PreNlsCreditInfoVO();
            preNlsCreditInfoPk.setApplySeq(nlsCreditInfoVO.getPreLmtApplySeq());
            PreNlsCreditInfoVO preNlsCreditInfoVO = preNlsCreditInfoService.queryByPk(preNlsCreditInfoPk);
            PsdSendTaxRecordVO psdSendTaxRecordVO = new PsdSendTaxRecordVO();
            psdSendTaxRecordVO.setTaxNo(preNlsCreditInfoVO.getTaxIdentificationNumber());
            psdSendTaxRecordVO.setApplySeq(psdCreditBackReqBean.getCrAppSrlNo());
            psdSendTaxRecordVO.setApplyStatus(psdCreditBackReqBean.getAprvlRsltFlg());
            String msg = "";
            if ("Y".equals(psdCreditBackReqBean.getAprvlRsltFlg().trim())) {
                msg = "纳税人授信成功";
            } else if ("N".equals(psdCreditBackReqBean.getAprvlRsltFlg().trim())) {
                msg = "纳税人授信失败";
            } else {
                msg = "纳税人请重新申请授信";
            }
            psdSendTaxRecordVO.setApplyMsg(msg);
            psdSendTaxRecordVO.setSendType("1");
            psdSendTaxRecordVO.setBizDate(pubSysInfoService.getOpenday(BaseConstant.SYS_ID_1001));
            psdSendTaxRecordVO.setHandStatus("N");
            psdSendTaxRecordVO.setHandNum(0);
            psdSendTaxRecordVO.setCreateTime(new Date());
            psdSendTaxRecordService.insert(psdSendTaxRecordVO);
        } catch (Exception ex) {
            logger.error("还款成功插入回写税局表发生异常",ex);
        }
    }


    private void clearPreOccupied(String sxApplySeq) {
        try {
            quotaCheckService.clearPreOccupied(sxApplySeq);
        } catch (Exception e) {
            logger.error("授信申请清除预占用额度发生异常",e);
        }
    }


    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("获取 ESB请求系统头和请求应用头对象!");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    @ModelAttribute("psdCreditBackReqBean")
    public PsdCreditBackReqBean getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("获取 ESB请求体！");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, PsdCreditBackReqBean.class);
    }

    @Autowired
    private PsdCreditBackService psdApplyBackService;
}